//
//  CalendarViewController.swift
//  GreenDeal
//
//  Created by Moennig Q on 12/12/2022.
//

import UIKit
import RxSwift
import RxCocoa
import MJRefresh
import SwiftyJSON
import HandyJSON
import RxGesture
class CalendarViewController: BaseViewController {
    let disposeBag = DisposeBag()
    let customView = CalendarView()
    var firstFlag: Bool = true
    var header: MJRefreshNormalHeader!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view = self.customView
        self.header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(headerLoad(_:)))
        self.customView.tableView.mj_header = self.header
        //点击头像
        self.customView.topCommonView.avatarImageView.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            InstallationDetailVCHelper.shared.toMeViewController(strongSelf)
        }).disposed(by: self.disposeBag)
        //
        self.customView.loadFaildView.retryBtn.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            strongSelf.loadAllData(loadWeatherFlag: true, loadJobsListPerDayFlag: true)
        }).disposed(by: self.disposeBag)
        //选择哪个job
        self.customView.tableView.rx.itemSelected.bind { [weak self] (indexPath) in
            guard let strongSelf = self else {return}
            //记录Crash log时的pvd id和gwt id
            let model: InstallationListModel = strongSelf.customView.jobsDataObserver.value[indexPath.row]
            SentryHelper().setCrashLogCustomInfo(pvdId: model.pvd_id ,gwtNo: model.gwt_id)
            JobDetailModelHelper.shared.jobDetailModel = PVDDetailModel()
            JobDetailModelHelper.shared.jobDetailModel.pvd_id = model.pvd_id
            JobDetailModelHelper.shared.jobDetailModel.gwt_id = model.gwt_id
            JobDetailModelHelper.shared.jobDetailModel.owner_address.type_name = model.full_name
            if model.solar_water_heater {
                let vc = SWHDetailViewController()
                vc.reloadPVDsListClosure = {[weak self] in
                    guard let strongSelf = self else { return  }
                    strongSelf.loadInstallationListByGWTID(JobDetailModelHelper.shared.jobDetailModel.gwt_id)
                }
                vc.hidesBottomBarWhenPushed = true
                strongSelf.navigationController?.pushViewController(vc, animated: false)
            }else{
                
                let vc = JobDetailViewController()
                vc.reloadPVDsListClosure = {[weak self] in
                    guard let strongSelf = self else { return  }
                    strongSelf.loadInstallationListByGWTID(JobDetailModelHelper.shared.jobDetailModel.gwt_id)
                }
                vc.hidesBottomBarWhenPushed = true
                strongSelf.navigationController?.pushViewController(vc, animated: false)
            }
            
        }.disposed(by: self.disposeBag)
        //选择某一天，加载job list数据
        self.customView.selectDateClosure = {[weak self]  in
            guard let strongSelf = self else {return}
            strongSelf.loadAllData(loadWeatherFlag: true, loadJobsListPerDayFlag: true)
        }
        //日历翻页，获取整个月测job cnt, 刷新
        self.customView.calendarPageClosure = {[weak self] (date) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.showLoadingView()
            strongSelf.loadJobsCnt(strongSelf.customView.calendar.currentPage) { code, errMsg in
                ModelViewUtil.shared.hideLoadingView()
                if errMsg == ""{
                    strongSelf.customView.calendar.reloadData()
                    strongSelf.customView.selectDate = date
                    strongSelf.loadAllData(loadWeatherFlag: true, loadJobsListPerDayFlag: true)
                }
            }
        }
        //
        self.loadAllData(loadWeatherFlag: true, loadJobsListPerDayFlag: true)
    }
    //MARK: - 根据GWTID查找installation list,刷新当前list
    fileprivate func loadInstallationListByGWTID(_ gwtID: String, closure: ((InstallationListModel)->Void)? = nil){
        //set block
        let vm = JobsListService()
        vm.setBlockAfterNetwork({[weak self] (result, _) -> Void in
            //data list
            guard let strongSelf = self else {return }
            guard let res = result else {return}
            let json = JSON(res)
            if let list = JSONDeserializer<InstallationListModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<InstallationListModel>, list.count > 0{
                var pvdsList = strongSelf.customView.jobsDataObserver.value
                if let index = pvdsList.firstIndex(where: {$0.gwt_id == JobDetailModelHelper.shared.jobDetailModel.gwt_id}) {
                    pvdsList[index] = list[0]
                    strongSelf.customView.jobsDataObserver.accept(pvdsList)//
                }
            }
        }) { (code, error) -> Void in
        }
        let combineStr = "?page=1&gwt_id=" + gwtID
        vm.getInstallationsListForV2(combineStr,cacheFlag: false)
    }
    let group = DispatchGroup()
    //MARK: - 加载当天所有数据
    func loadAllData(loadWeatherFlag: Bool, loadJobsListPerDayFlag: Bool, loadingFlag: Bool = true){
        var errCode = ""
        var errMsg = ""
        if loadingFlag {
            ModelViewUtil.shared.showLoadingView(R.string.localizable.loading())
        }
        
        //2.jobs cnt list
        group.enter()
        DebugLog("loadJobsCnt: 0")
        self.loadJobsCnt(self.customView.selectDate) { [weak self](code,msg) in
            if code != "" || errMsg != ""{
                errCode = code
                errMsg = msg
            }
            DebugLog("loadJobsCnt: 1")
            self?.group.leave()
        }
        //3.jobs list for one date
        if loadJobsListPerDayFlag{
            self.group.enter()
            DebugLog("loadJobListByDate: 0")
            self.loadJobListByDate() { [weak self](code,msg) in
                if code != "" || errMsg != ""{
                    errCode = code
                    errMsg = msg
                }
                DebugLog("loadJobListByDate: 1")
                self?.group.leave()
            }
        }
        self.group.notify(queue: DispatchQueue.main) {
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            self.header.endRefreshing()
            if errCode != "" || errMsg != "" {
                self.customView.showFaildView()
                Tool().showErrorInfo(errCode,errMsg)
            }else{
                self.customView.calendar.reloadData()
                self.customView.tableView.reloadData()
                self.customView.tableView.checkIfCalendarShowNoDataView(self.customView.jobsDataObserver.value.count)
                self.customView.showDetailView()
            }
        }
    }
    //MARK: - 加载某个月或week的日期内的job数量
    private func loadJobsCnt(_ date: Date,closure: ((String,String)->Void)? = nil){
        let service = CreateJobService()
        service.setBlockAfterNetwork { [weak self] (result, otherInfo) in
            guard let strongSelf = self else { return  }
            if let data = result as? [CreateJobStatusModel]{
                let list = data.filter({[PVDJobStatusName.scheduled.rawValue, PVDJobStatusName.installing.rawValue,PVDJobStatusName.unqualified.rawValue,PVDJobStatusName.installed.rawValue].contains($0.status)})
                strongSelf.customView.jobsList = list
            }
            closure?("","")
        } errorBlock: {  code, error in
            closure?(code,error)
        }
        let beginDate = DateUtil().getServeralYearOfToday(date: date, month: -1)
        let endDate = DateUtil().getServeralYearOfToday(date: date, month: 1)
        service.getJobStatusList(beginDate, endDate: endDate)
    }
    //MARK: - 加载某个月或week的日期内的job数量
    private func loadJobListByDate(closure: ((String,String)->Void)? = nil){
        //set block
        let vm = JobsListService()
        vm.setBlockAfterNetwork({ (result, otherInfo) -> Void in
            //data list
            guard let res = result else {return}
            let json = JSON(res)
            if let data = JSONDeserializer<InstallationListModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<InstallationListModel>{
                self.customView.jobsDataObserver.accept(data)
            }
            closure?("","")
        }) { (code, error) -> Void in
            closure?(code,error)
        }
        let installDate = DateUtil().getDatetimeStr(self.customView.selectDate,format: "yyyy-MM-dd")
        let combineStr = "?page=1&per_page=100&scheduler_time=" + installDate
        vm.getInstallationsListForV2(combineStr,cacheFlag: false)
    }
    @objc func headerLoad(_ header: MJRefreshNormalHeader){
        self.loadAllData(loadWeatherFlag: true, loadJobsListPerDayFlag: true,loadingFlag: false)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    override func viewDidAppear(_ animated: Bool) {
        if self.firstFlag {//第一次打开界面才调用
            self.firstFlag = false
            self.customView.switchCalendarModeBtnClick()
        }
        
    }
}
